package com.ttloner1.preparedstatement;

import com.ttloner2.bean.Customer;
import com.ttloner1.util.JDBCUtils;
import org.junit.Test;

import java.io.IOException;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;

/**
 * @author TTLoner
 * @date 2021/6/21 14:02
 * @description
 * 用于查询操作的测试
 */

public class SearchTest {
    /*
     * @author: TTLoner
     * @time: 2021/6/21 17:18
     * @description:通用的查操作
     */
    public ArrayList<Customer> Query(String sql, Object[] args) throws SQLException, IOException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
        Connection conn = JDBCUtils.getConnection();
        PreparedStatement ps = conn.prepareStatement(sql);
        for(int i=0;i<args.length;i++){
            ps.setObject(i+1,args[i]);
        }
        //获取结果集
        ResultSet resultSet = ps.executeQuery();
        //获取结果的元数据：
        ResultSetMetaData metaData = resultSet.getMetaData();
        //通过元数据获取列数
        int columnCount=metaData.getColumnCount();
        ArrayList<Customer> list = new ArrayList<>();
        while(resultSet.next()) {//next()判断结果集下一条是否有数据
            Customer customer = new Customer();
            for(int i=0;i<columnCount;i++){
                Object o = resultSet.getObject(i + 1);
                //获取每个列的列名
                String name = metaData.getColumnName(i + 1);
                //通过反射
                Field field = Customer.class.getDeclaredField(name);
                field.setAccessible(true);
                field.set(customer,o);
            }
            list.add(customer);
        }
        JDBCUtils.closeConnection(conn,ps,resultSet);
        return list;
    }
    @Test
    public void test() throws SQLException, IOException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
        String sql="select name,email,id,birth from customers where name=?";
        Object[] args={"汪峰"};
        ArrayList<Customer> list = Query(sql, args);
        System.out.println(list);
    }
}
